package com.zlp.api.test.config;

import com.zlp.api.test.config.ElasticsearchTask;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;

import java.io.IOException;
import java.util.Objects;

public class ConnectElasticsearch{

    public static void connect(ElasticsearchTask task){
        // 创建客户端对象
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http")));
        try {
            task.doSomething(client);

            client.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            // 关闭客户端连接
            try {
                if (Objects.nonNull(client)) {
                    client.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
